import Vue from "vue";
import VueRouter from "vue-router";
import Layout from '@/views/layout.vue'
import store from '@/store/index'
import { Notification, MessageBox, Message, Loading } from 'element-ui'

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    component: Layout,
    name: 'Layout',
    redirect: 'index',
    meta: {
      title: '设备租赁'
    },
    children: [
      {
        path: 'index',
        component: () => import('@/views/index.vue'),
        name: 'Index',
        meta: {
          title: '首页',
          noLogin: true
        }
      },
      {
        path: 'productList/factory',
        component: () => import('@/views/product/productList.vue'),
        name: 'ProductListFactory',
        meta: {
          title: '厂家货源',
          noLogin: true
        }
      },
      {
        path: 'productList/used',
        component: () => import('@/views/product/productList.vue'),
        name: 'ProductListUsed',
        meta: {
          title: '二手货源',
          noLogin: true
        }
      }, {
        path: 'productList/rentOut',
        component: () => import('@/views/product/productList.vue'),
        name: 'ProductListRentOut',
        meta: {
          title: '租赁货源',
          noLogin: true
        }
      },
      {
        path: '/demandHall',
        name: 'demandHall',
        component: () => import('@/views/demand/demandHall.vue'),
        meta: {
          title: '需求大厅',
          noLogin: true
        }
      },
      {
        path: 'productDetail/:from',
        component: () => import('@/views/product/productDetail.vue'),
        name: 'ProductDetail',
        meta: {
          title: '设备详情',
          fatherPage: ['Index', 'ProductListFactory', 'ProductListUsed', 'ProductListRentOut', 'collect'],
          noLogin: true
        }
      },
      {
        path: 'orderSubmit/:from',
        component: () => import('@/views/order/orderSubmit.vue'),
        name: 'orderSubmit',
        meta: {
          title: '提交订单',
          fatherPage: ['ProductDetail']
        }
      }, {
        path: '/addressInfo',
        component: () => import('@/views/user/addressInfo.vue'),
        name: 'addressInfo',
        meta: {
          title: '地址信息',
          fatherPage: ['orderSubmit'],
        }
      }, {
        path: '/productDiff',
        name: 'productDiff',
        component: () => import('@/views/product/productDiff.vue'),
        meta: {
          title: '设备对比',
          fatherPage: ['ProductDetail']
        }
      }, {
        path: '/demandDetail/:from/:id',
        name: 'demandDetail',
        component: () => import('@/views/demand/demandDetail.vue'),
        meta: {
          title: '需求详情',
          fatherPage: ['Index', 'demandHall']
        }
      }, {
        path: '/demandPublish/:from',
        name: 'demandPublish',
        component: () => import('@/views/demand/demandPublish.vue'),
        meta: {
          title: '发布需求',
          noLogin: false,
          fatherPage: ['Index']
        }
      }, {
        path: '/storeList/:from',
        name: 'storeList',
        component: () => import('@/views/store/storeList.vue'),
        meta: {
          title: '店铺列表',
          noLogin: false,
          fatherPage: ['Index']
        }
      }, {
        path: '/storeDetail/:from/:id',
        name: 'storeDetail',
        component: () => import('@/views/store/storeDetail.vue'),
        meta: {
          title: '店铺详情',
          noLogin: false,
          fatherPage: ['Index', 'storeList', 'ProductDetail', 'collect']
        }
      },
      {
        path: '/publishType',
        name: 'publishType',
        component: () => import('@/views/product/publishType.vue'),
        meta: {
          title: '发布商品',
        }
      },
      {
        path: '/productFormSell/:from',
        name: 'productFormSell',
        component: () => import('@/views/product/productFormSell.vue'),
        meta: {
          title: '出售',
          fatherPage: ['publishType']
        }
      },
      {
        path: '/skuList/:from',
        name: 'skuList',
        component: () => import('@/views/product/skuList.vue'),
        meta: {
          title: '设置规格',
          fatherPage: ['productFormSell']
        }
      },
      {
        path: '/productFormRentOut/:from',
        name: 'productFormRentOut',
        component: () => import('@/views/product/productFormRentOut.vue'),
        meta: {
          title: '出租',
          fatherPage: ['publishType']
        }
      },
      {
        path: '/user',
        name: 'user',
        component: () => import('@/views/user/index.vue'),
        meta: {
          title: '个人中心',
          noLogin: false
        },
        children: [
          {
            path: '/vip',
            name: 'vip',
            component: () => import('@/views/user/vip.vue'),
            meta: {
              title: '会员中心'
            }
          },
          {
            path: '/orderList/self',
            name: 'orderListSelf',
            component: () => import('@/views/user/orderList.vue'),
            meta: {
              title: '购买订单'
            }
          }, {
            path: '/orderList/sell',
            name: 'orderListSell',
            component: () => import('@/views/user/orderList.vue'),
            meta: {
              title: '商家订单'
            }
          }, {
            path: '/orderDetail/:from',
            name: 'orderDetail',
            component: () => import('@/views/user/orderDetail.vue'),
            meta: {
              title: '订单详情'
            }
          }, {
            path: '/demandList',
            name: 'demandList',
            component: () => import('@/views/user/demandList.vue'),
            meta: {
              title: '需求管理'
            }
          }, {
            path: '/mineDmandDetail/:id',
            name: 'mineDemandDetail',
            component: () => import('@/views/user/demandDetail.vue'),
            meta: {
              title: '需求详情',
            }
          }, {
            path: '/demandEdit/:id',
            name: 'demandEdit',
            component: () => import('@/views/user/demandEdit.vue'),
            meta: {
              title: '需求编辑',
            }
          }, {
            path: '/userProductList/:from',
            name: 'userProductList',
            component: () => import('@/views/user/productList.vue'),
            meta: {
              title: '厂商管理'
            }
          },  {
            path: '/mineProductEdit/:id',
            name: 'mineProductEdit',
            component: () => import('@/views/user/productEdit.vue'),
            meta: {
              title: '商品编辑',
            }
          }, {
            path: '/mineProductEditRentout/:id',
            name: 'mineProductEdit',
            component: () => import('@/views/user/ProductEditRentout.vue'),
            meta: {
              title: '商品编辑',
            }
          }, {
            path: '/skuEdit',
            name: 'mineSkuList',
            component: () => import('@/views/user/skuEdit.vue'),
            meta: {
              title: '商品编辑',
            }
          },{
            path: '/wallet',
            name: 'wallet',
            component: () => import('@/views/user/wallet.vue'),
            meta: {
              title: '我的钱包'
            }
          }, {
            path: '/balanceRecord',
            name: 'balanceRecord',
            component: () => import('@/views/user/balanceRecord.vue'),
            meta: {
              title: '余额明细',
            }
          }, {
            path: '/withdraw',
            name: 'withdraw',
            component: () => import('@/views/user/withdraw.vue'),
            meta: {
              title: '提现',
            }
          }, {
            path: '/collect',
            name: 'collect',
            component: () => import('@/views/user/collect.vue'),
            meta: {
              title: '我的收藏',
            }
          }, {
            path: '/shopInfo',
            name: 'shopInfo',
            component: () => import('@/views/user/shopInfo.vue'),
            meta: {
              title: '我的店铺',
            }
          }, {
            path: '/registerUser2Enterprise',
            component: () => import('@/views/user/registeruser2Enterprise.vue'),
            meta: {
              title: '成为企业账号',
              noLogin: false
            }
          },{
            path: '/reportList',
            name: 'reportList',
            component: () => import('@/views/user/reportList.vue'),
            meta: {
              title: '我的举报',
            }
          }, {
            path: '/realNameForm',
            name: 'realNameForm',
            component: () => import('@/views/user/realNameForm.vue'),
            meta: {
              title: '实名认证',
            }
          }, {
            path: '/helpCenter',
            name: 'helpCenter',
            component: () => import('@/views/user/helpCenter.vue'),
            meta: {
              title: '帮助中心',
            }
          }
        ]
      },
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/user/login.vue'),
    meta: {
      title: '登录',
      noLogin: true
    }
  },
  {
    path: '/register',
    component: () => import('@/views/user/register.vue'),
    meta: {
      title: '注册',
      noLogin: true
    }
  },
  {
    path: '/richText',
    component: () => import('@/views/other/ricthText.vue'),
    meta: {
      title: '协议',
      noLogin: true
    }
  }
];

// 防止连续点击多次路由报错
let routerPush = VueRouter.prototype.push;
let routerReplace = VueRouter.prototype.replace;
// push
VueRouter.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(err => err)
}
// replace
VueRouter.prototype.replace = function push(location) {
  return routerReplace.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes,
  scrollBehavior (to, from, savedPosition) {
    return { x: 0, y: 0 } // 返回{x: 0, y: 0}表示每次都将页面滚动到顶部
  }
});


const allRouter = []
function getAllRoute(routes) {
  for (let i = 0; i < routes.length; i++) {
    if (routes[i].children && routes[i].children.length) {
      getAllRoute(routes[i].children)
    } else {
      const r = {
        path: routes[i].path,
        meta: routes[i].meta,
        name: routes[i].name
      }
      allRouter.push(r)
    }
  }
}

if(!store.getters.allRouter.length){
  getAllRoute(router.options.routes);
  store.commit('app/SET_ALLROUTER', allRouter)
}


function getFatherRoute(route, result = []) {

  let fatherStr = ''
  if (route.meta.fatherPage) {
    if ((typeof route.meta.fatherPage) === 'object') {
      fatherStr = route.meta.fatherPage.find(item => item === route.params.from)
    } else {
      fatherStr = route.meta.fatherPage
    }
  }
  if (fatherStr) {
    const father = store.getters.allRouter.find(item => item.name === fatherStr)
    if (father) {
      result.unshift(father)
      getFatherRoute(father, result)
    }
  }
}

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }

  if(!to.meta.noLogin && !store.getters.token){
    document.title = '登录'
    Message({ message: '您还未登录，请先登录', type: 'error', duration: 2 * 1000 })
    setTimeout(() => {
      store.dispatch('user/LogOut')
      next({
        path: '/login',
      })
    }, 800);
   
  }

  let arr = []

  // 刷新
  if (!from.name) {
    arr = store.getters.breadCrumbList
  }
  else {

    const routeIndex = store.getters.allRouter.findIndex(item => item.name === to.name)
    store.getters.allRouter.splice(routeIndex, 1, {
        fullPath: to.fullPath, 
        path: to.path,
        meta: to.meta,
        params: to.params,
        query: to.query,
        name: to.name
    });
    store.commit('app/SET_ALLROUTER', store.getters.allRouter)
    //设置面包屑
    getFatherRoute(to, arr)
    arr.push(to)
  }
  store.commit('app/SET_BREADCRUMB', arr);
  next()
})

export default router;
